package com.ityueqiangu.system.controller;

import com.ityueqiangu.core.constant.Constants;
import com.ityueqiangu.core.enums.CommonEnum;
import com.ityueqiangu.core.exception.BizException;
import com.ityueqiangu.core.util.ServletUtils;
import com.ityueqiangu.core.util.file.FileUploadUtils;
import com.ityueqiangu.core.web.result.ResultDataUtil;
import com.ityueqiangu.core.web.result.ResultInfo;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

/**
 * @author Clever、xia
 * @title: FileController
 * @projectName art-exhibition-system
 * @description:
 * @date 2021-03-11 21:30
 */
@Controller
@RequestMapping(value = "/file")
public class FileController {

    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    @ResponseBody
    public ResultInfo uploadFile(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new BizException("文件不能为空");
        }
        // 上传文件路径
        String filePath = Constants.UPLOAD_FILE_PATH;
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = ServletUtils.getUrl() + fileName;
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("fileName", fileName);
        resultMap.put("url", url);
        return ResultDataUtil.createSuccess(CommonEnum.FILE_UPLOAD_SUCCESS).setData(resultMap);
    }

    /**
     * layui 文件上传
     */
    @PostMapping("/uploadImage")
    @ResponseBody
    public ResultInfo uploadImage(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new BizException("文件不能为空");
        }
        // 上传文件路径
        String filePath = Constants.UPLOAD_FILE_PATH;
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = ServletUtils.getUrl() + fileName;
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("title", fileName);
        resultMap.put("src", url);
        return ResultDataUtil.createSuccess(CommonEnum.FILE_UPLOAD_SUCCESS_LAYUI).setData(resultMap);
    }


    /**
     * 图片下载
     */
    @RequestMapping("showImageByPath")
    public ResponseEntity<Object> showImageByPath(String path) {
        return FileUploadUtils.createResponseEntity(path);
    }
}
